#include <QtDebug>
#include <QMutex>
#include <QDateTime>

#include "config.h"
#include "netter.h"
#include "scheduler.h"

Netter *Netter::snetter = 0;
Scheduler *Netter::sscheduler = 0;
Client *Netter::sclient = 0;

Netter *Netter::instance() {

    return snetter;
}

Scheduler *Netter::scheduler()
{
    if (!sscheduler) {
        sscheduler = new Scheduler();
    }
    return sscheduler;
}
Client *Netter::client()
{
    if (!sclient) {
        sclient = new Client();
    }
    return sclient;
}

Netter::Netter(QObject *parent) :
    QObject(parent) {

		snetter = this;
		
		// creo lo scheduler per la 
		// gestione dei comandi
		/*
		QObject::connect(&(scheduler), 
						 SIGNAL(event_new_command(const Command *)), 
						 this, 
						 SLOT(process_new_command(const Command *)),
						 Qt::DirectConnection); // Qt::DirectConnection -> necessario che sia sincrono
		*/
		


}

Netter::~Netter() {

	if(sscheduler)
		delete sscheduler;
	if(sclient)
		delete sclient;
}




void Netter::trace(QString header, QString message, LogLevel level) {

	QString final;
	final.append(QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss.zzz - "));
	final.append(header);
	final.append(":");
	final.append(message);
	final.append(" - ");	
	final.append((int)level);
	final.append("\n");
	qDebug() << final;
}


void Netter::start() {
	
	Netter::trace("Netter", "Avviamento network...", LogLevelInformation);
	Netter::client()->start();
	Netter::trace("Netter", "Avviamento scheduler...", LogLevelInformation);
	Netter::scheduler()->start();
	
}


void Netter::processNewCommand(const Message *c) {

	/*
	// valuto il tipo di comando
	switch (c->type) {

		case Command::Message:
		{
			qDebug() << "Messaggio," << c->type;
			break;
		}	
			
		case Command::RttmOpenConnection:
		{
			QTcpSocket *tcpSocket 
					= new QTcpSocket();
			if (!tcpSocket->setSocketDescriptor(c->data.socketHandle)) {
				qDebug() << "Errore nella creazione del socket";
				break;
			}

			// aggiungo il socket alla collezione
			this->_rttm_sockets.append(tcpSocket);
			qDebug() << "Socket " 
					<< c->data.socketHandle 
					<< " aggiunto alla collezione rttm";
			break;

		}
		case Command::RttmDataArrival:
			
			break;
		default:
			break;
			
	}
	qDebug() << c->msg;
	 
	 */


}


void Netter::rttmNewConnection(int handle) {
	/*
	qDebug() << "Nuova connessione rttm: " << handle;
	Command *c = new Command();
	c->type = Command::RttmOpenConnection;
	c->data.socketHandle = handle;
	netter.scheduler.push_new_command(c);
	 */
	
}
void Netter::rttmDataArrival(const QString &data) {
	
	qDebug() << "Dati rttm: " << data;

}
void Netter::commandsNewConnection(int handle) {
	
	qDebug() << "Nuova connessione command: ";

}
void Netter::commandsDataArrival(const QString &data) {
	
	qDebug() << "Dati command: " << data;

}